package com.jkhan.demo.deadlock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName LockTest
 * @Description LockTest
 * @Author hjk
 * @Date 2022/1/9 21:22
 **/
public class LockTest {
    public static void main(String[] args) {
        Window window = new Window();

        Thread t1 = new Thread(window);
        Thread t2 = new Thread(window);
        Thread t3 = new Thread(window);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}

class Window implements Runnable {
    private int ticket = 100;

    private ReentrantLock lock = new ReentrantLock();//参数fair，是否公平（先进先出）

    @Override
    public void run() {
        while (true) {
            try {

                //锁定
                lock.lock();

                if (ticket > 0) {
                    try {
                        Thread.currentThread().sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + " : 售票，票号为： " + ticket);
                    ticket--;
                } else {
                    break;
                }
            } finally {
                //解锁
                lock.unlock();
            }
        }
    }
}
